package com.tianyalei.wolf.mddesignlib.utils;

import android.content.Context;
import android.media.MediaScannerConnection;
import android.os.Environment;
import android.os.Handler;

import com.facebook.binaryresource.FileBinaryResource;
import com.facebook.cache.common.SimpleCacheKey;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.tianyalei.wolf.mddesignlib.utils.media.JDMediaScannerConnectionClient;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * Created by wolf on 2016/4/7.
 */
public class FileUtil {
    public static void savePic(Context context, String appName, String url) {
        try {
            //根据url或者fresco加载的图片缓存地址
            FileBinaryResource resource = (FileBinaryResource) Fresco.getImagePipelineFactory().getMainDiskStorageCache().getResource(new SimpleCacheKey(url));
            File oldfile = resource.getFile();

            String dirPath = Environment.getExternalStorageDirectory() + File.separator + appName;
            String newPath = dirPath + File.separator + System.currentTimeMillis() + getExt(url);
            File file = new File(dirPath);
            if (!file.exists()) {
                file.mkdirs();
            }

            int bytesum = 0;
            int byteread = 0;
            if (oldfile.exists() && Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { //文件存在时
                InputStream inStream = new FileInputStream(oldfile); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1024];
                int length;
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }

            ToastUtil.showToast(context, "图片已保存到SD卡" + appName + "目录下");

            notifySystem(context, newPath);

        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.showToast(context, "图片保存失败，请重试");
        }
    }

    /**
     * 通知系统图库刷新
     *
     * @param context
     * @param newPath
     */
    private static void notifySystem(Context context, String newPath) {
        JDMediaScannerConnectionClient connectionClient = new JDMediaScannerConnectionClient(new File(newPath));
        final MediaScannerConnection connection = new MediaScannerConnection(context, connectionClient);
        connectionClient.setMediaScannerConnection(connection);
        connection.connect();

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (connection != null && connection.isConnected()) {
                    connection.disconnect();
                }
            }
        }, 500);
    }

    /**
     * 获取后缀名
     *
     * @param url
     * @return
     */
    private static String getExt(String url) {
        //http://www.th7.cn/Program/Android/201411/316443
        int index = url.lastIndexOf(".");
        String result = url.substring(index, url.length());
        if (result.length() <= 6) {
            return result;
        } else {
            return ".png";
        }
    }


}
